package com.atxwq.shop.cart.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSON;
import com.atxwq.shop.cart.service.CartService;
import com.atxwq.shop.feign.product.ProductFeignClient;
import com.atxwq.shop.model.entity.h5.CartInfo;
import com.atxwq.shop.model.entity.product.ProductSku;
import com.atxwq.shop.model.entity.user.UserInfo;
import com.atxwq.shop.model.vo.common.RedisCodeEnum;
import com.atxwq.shop.model.vo.common.Result;
import com.atxwq.utils.AuthContextUtil;
import com.github.xiaoymin.knife4j.core.util.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.data.redis.core.RedisTemplate;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Description TODO
 * @Date 2025/5/22 21:40
 * @Created by 12336
 */

@Service
public class CartServiceImpl implements CartService {

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Autowired
    private ProductFeignClient productFeignClient;



    private String getCartKey(Long userId) {
        //定义key user:cart:userId
        return RedisCodeEnum.USER_LOGIN_TOKEN.toString() + userId;
    }

    /**
     * 添加商品到购物车
     * @param skuId
     * @param skuNum
     */
    @Override
    public void addToCart(Long skuId, Integer skuNum) {
//        1.获取用户id
        UserInfo userInfo = AuthContextUtil.getUserInfo();
        Long userId = userInfo.getId();
        String cartKey = this.getCartKey(userId);

//        2.从redis中获取购物车数据
        //hash类型（key:用户id, field:skuId, value:skuInfo）
        Object cartInfoObj = redisTemplate.opsForHash().get(cartKey, String.valueOf(skuId));

//        3.判断购物车中是否有此商品,如果有则数量相加
        CartInfo cartInfo = null;
        if(cartInfoObj != null){
             cartInfo = JSON.parseObject(cartInfoObj.toString(), CartInfo.class);
             cartInfo.setSkuNum(cartInfo.getSkuNum() + skuNum);
             //设置选中状态
             cartInfo.setIsChecked(1);
             cartInfo.setUpdateTime(new Date());
        }else {
//         4.如果没有则添加到购物车（放入redis）中 通过远程调用实现商品sku信息
            cartInfo = new CartInfo();

            // 购物车数据是从商品详情得到 {skuInfo}
            ProductSku productSku = productFeignClient.getBySkuId(skuId) ;
            cartInfo.setCartPrice(productSku.getSalePrice());
            cartInfo.setSkuNum(skuNum);
            cartInfo.setSkuId(skuId);
            cartInfo.setUserId(userId);
            cartInfo.setImgUrl(productSku.getThumbImg());
            cartInfo.setSkuName(productSku.getSkuName());
            cartInfo.setIsChecked(1);
            cartInfo.setCreateTime(new Date());
            cartInfo.setUpdateTime(new Date());

        }
        // 将商品数据存储到购物车中
        redisTemplate.opsForHash().put(cartKey, String.valueOf(skuId), JSON.toJSONString(cartInfo));
    }

    /**
     * 查询购物车列表
     * @return
     */
    @Override
    public List<CartInfo> getCartList() {
        //1.构建查询redis的key,根据userId
        Long userId = AuthContextUtil.getUserInfo().getId();
        String cartKey = this.getCartKey(userId);

        //2.从redis中获取数据
        List<Object> valueList = redisTemplate.opsForHash().values(cartKey);

        //3.将数据转换为List<CartInfo>
        if(!CollectionUtils.isEmpty(valueList)){
            List<CartInfo> cartInfoList = valueList.stream().map(cartInfoObj ->
                JSON.parseObject(cartInfoObj.toString(), CartInfo.class)
            ).collect(Collectors.toList());
            return cartInfoList;
        }

        return new ArrayList<>();
    }

    /**
     * 删除购物车
     * @param skuId
     */
    @Override
    public void deleteCart(Long skuId) {
        //1.获取当前登录用户id
        Long userId = AuthContextUtil.getUserInfo().getId();
        String cartKey = this.getCartKey(userId);
        //2.根据cartKey删除redis中的数据
        redisTemplate.opsForHash().delete(cartKey, String.valueOf(skuId));

    }

    /**
     * 更新选中状态
     * @param skuId
     * @param isChecked
     */
    @Override
    public void checkCart(Long skuId, Integer isChecked) {
        //1.获取当前登录用户id
        Long userId = AuthContextUtil.getUserInfo().getId();
        String cartKey = this.getCartKey(userId);

        Boolean hasKey = redisTemplate.opsForHash().hasKey(cartKey, String.valueOf(skuId));
        if(hasKey){
            CartInfo cartInfo = JSON.parseObject(redisTemplate.opsForHash().get(cartKey, String.valueOf(skuId)).toString(), CartInfo.class);
            cartInfo.setIsChecked(isChecked);
            cartInfo.setUpdateTime(new Date());
            redisTemplate.opsForHash().put(cartKey, String.valueOf(skuId), JSON.toJSONString(cartInfo));
        }

    }

    /**
     * 购物车全选
     * @param isChecked
     */
    @Override
    public void allCheckCart( Integer isChecked) {
        //1 获取当前登录的用户数据
        Long userId = AuthContextUtil.getUserInfo().getId();
        String cartKey = getCartKey(userId);

        //2. 获取购物车数据
        List<Object> objList = redisTemplate.opsForHash().values(cartKey);
        //利用stream流的方法循环遍历购物车数据进行类型转换并更改选中状态存入redis中
        if(!CollectionUtils.isEmpty(objList)){
            objList.stream().map(cartInfoJson -> {
                CartInfo cartInfo = JSON.parseObject(cartInfoJson.toString(), CartInfo.class);
                cartInfo.setIsChecked(isChecked);
                return cartInfo;
            }).forEach(cartInfo -> redisTemplate.opsForHash().put(cartKey,
                                                                        String.valueOf(cartInfo.getSkuId()),
                                                                        JSON.toJSONString(cartInfo)) );
        }


    }

    /**
     * 清空购物车
     */
    @Override
    public void clearCart() {
        //1 获取当前登录的用户数据
        Long userId = AuthContextUtil.getUserInfo().getId();
        String cartKey = getCartKey(userId);
        redisTemplate.delete(cartKey);
    }

    /**
     * 远程调用
     * @return
     */
    @Override
    public List<CartInfo> getAllCkecked() {
        //获取用户id,构建key
        Long userId = AuthContextUtil.getUserInfo().getId();
        String cartKey = getCartKey(userId);

        List<Object> objList = redisTemplate.opsForHash().values(cartKey);
        if(!CollectionUtils.isEmpty(objList)){
            List<CartInfo> cartInfoList = objList.stream().map(object ->  JSON.parseObject(object.toString(), CartInfo.class))
                    .filter(cartInfo -> cartInfo.getIsChecked() == 1) //选中条件
                    .collect(Collectors.toList());
            return cartInfoList;
        }
        return new ArrayList<>();
    }

    /**
     * 远程调用
     */
    @Override
    public void deleteChecked() {
        //获取用户id,构建key
        Long userId = AuthContextUtil.getUserInfo().getId();
        String cartKey = getCartKey(userId);
        //根据key获取购物车列表
        List<Object> objectList = redisTemplate.opsForHash().values(cartKey);

        //删除选中的商品：stream 过滤出选中的商品
        if(!CollectionUtils.isEmpty(objectList)) {
            objectList.stream().map(cartInfoJSON -> JSON.parseObject(cartInfoJSON.toString(), CartInfo.class))
                    .filter(cartInfo -> cartInfo.getIsChecked() == 1)
                    .forEach(cartInfo -> redisTemplate.opsForHash().delete(cartKey , String.valueOf(cartInfo.getSkuId())));
        }

    }


}
